package com.lft.freshordering.controller;

import com.lft.freshordering.entity.VO.BilVO;
import com.lft.freshordering.entity.VO.OrderVO;
import com.lft.freshordering.entity.Orders;
import com.lft.freshordering.entity.VO.BillAllVO;
import com.lft.freshordering.response.R;
import com.lft.freshordering.response.StatusEnum;
import com.lft.freshordering.service.IOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;


import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tyhxzy
 * @since 2024-12-02
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private IOrdersService ordersService;

    @GetMapping("/selectAllOrders")
    public R selectAllOrders() {
        List<OrderVO> orders = ordersService.selectAllOrders();
        return R.success(orders);
    }

    @PostMapping("/selectOrders/{oid}")
    public R selectOrders(@PathVariable String oid) {
        OrderVO order = ordersService.selectOrders(oid);
        System.out.println(order);
        return R.success(order);
    }

    @GetMapping("/selectAllOrders1")
    public R selectAllOrders1() {
        List<OrderVO> orders = ordersService.selectAllOrders1();
        return R.success(orders);
    }

    @GetMapping("/selectAllOrders2")
    public R selectAllOrders2() {
        List<OrderVO> orders = ordersService.selectAllOrders2();
        return R.success(orders);
    }

    //    @PostMapping("/updateDelivery/{delivery}/{id}")
//    public R updateDelivery(@PathVariable String delivery,@PathVariable Integer id){
//        int i = ordersService.updateDelivery(delivery, id);
//        return R.success(i);
//    }
    @PostMapping("/updateStatus/{id}")
    public R updateStatus(@PathVariable Integer id) {
        int i = ordersService.updateStatus(id);
        return R.success(i);
    }
    @PutMapping("/updateStatus1/{id}")
    public R updateStatus1(@PathVariable Integer id){
        int i = ordersService.updateStatus1(id);
        return R.success(i);
    }

    @PutMapping("/updateStatus11/{id}")
    public R updateStatus11(@PathVariable Integer id){
        int i = ordersService.updateStatus(id);
        return R.success(i);
    }
    @GetMapping("selrctorder/{uid}")
    public R getOrdersByUserId(@PathVariable Integer uid) {
        // 调用服务层方法，根据用户ID查询订单信息
        List<OrderVO> orders = ordersService.selectordersByiddym(uid);
        return R.success(orders);
    }

    @PutMapping("/updateStatus/{id}")
    public R updateOrderStatus(@PathVariable String id) {
        int i = ordersService.updateOrderStatus(id, "1"); // 状态值为 1
        if (i > 0) {
            return R.success("确认收货成功");
        } else {
            return R.error(StatusEnum.valueOf("FAILURE"));
        }
    }

    @GetMapping("/selectOrders1/{uid}")
    public R selectOrders1(@PathVariable Integer uid) {
        List<OrderVO> orders = ordersService.selectOrders1(uid);
        return R.success(orders);
    }

    @GetMapping("/selectOrders2/{uid}")
    public R selectOrders2(@PathVariable Integer uid) {
        List<OrderVO> orders = ordersService.selectOrders2(uid);
        return R.success(orders);
    }

    @PostMapping("/upload")
    public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file, @RequestParam("id") Integer id) throws IOException {
        // 检查订单是否存在
        OrderVO order = ordersService.selectOrders(id.toString());
        if (order == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("订单不存在");
        }

        // 处理文件上传
        byte[] bytes = handleFileUpload(file);
        System.out.println(bytes);

        // 更新订单交付信息
        int i = ordersService.updateDelivery(bytes, id); // 使用Base64字符串

        return ResponseEntity.ok(bytes);
    }

    private byte[] handleFileUpload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);

        // 文件类型
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println(fileType);

        // 检查文件类型是否支持
        if (!fileType.equalsIgnoreCase("png") && !fileType.equalsIgnoreCase("jpg")) {
            throw new IllegalArgumentException("Unsupported file type");
        }

        // 创建临时文件
        File tempFile = File.createTempFile("temp", file.getOriginalFilename());

        // 将上传的文件写入临时文件
        file.transferTo(tempFile);

        // 将文件转换为字节数组
        FileInputStream fis = new FileInputStream(tempFile);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 读取文件内容
        byte[] buf = new byte[1024];
        int len;
        while ((len = fis.read(buf)) != -1) {
            baos.write(buf, 0, len);
        }

        // 关闭输入输出流
        fis.close();
        baos.close();

        // 将字节数组转换为Base64编码
        byte[] bytes = baos.toByteArray();


        return bytes; // 返回Base64字符串而不是字节数组
    }


    @GetMapping("/getImage/{id}")
    public ResponseEntity<String> getImage(@PathVariable String id) {
        OrderVO order = ordersService.selectOrders(id);
        byte[] imageBytes = order.getDelivery();

        if (imageBytes == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("图片未找到");
        }

        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        return ResponseEntity.ok(base64Image);
    }


    @GetMapping("/autoConfirm")
    public String autoConfirmOrders() {
        ordersService.autoConfirmOrders();
        return "Orders auto confirmed successfully";
    }

//zjb向上
//-----------------------------------------------------------------------------------------------------------------------
//ght向下

    @GetMapping("/selectall")
    public R selectall() {
        BillAllVO selectall = ordersService.selectall();
        return R.success(selectall);
    }

    @RequestMapping("/selectuserorder/{shopname}")
    public R selectdatil(@PathVariable String shopname) {
        BilVO bilVOS = ordersService.selectorderbyuserid(shopname);
        return R.success(bilVOS);
    }

//ght向上
//-----------------------------------------------------------------------------------------------------------------------
//zwl向下

    /**
     * 更新订单的支付状态
     *
     * @param id 包含要更新的订单信息的对象，其中包含订单ID和支付状态等信息
     * @return 返回一个R对象，表示更新操作的结果
     */
//点击还款按钮
    @RequestMapping("/updatePaystate/{id}")
    public R updatePaystate(@RequestBody Map map) {
        System.out.println(map);
        int i = ordersService.updatePaystate(map);
        return R.success(1);
    }

    @RequestMapping("/updateRealpa")
    public R updateRealpay(@RequestBody Orders orders) {
        if (orders.getUid() == null) {
            return R.error(400, HtmlUtils.htmlEscape("id为空"));
        }
        if (orders.getRealpay() == null || orders.getRealpay() <= 0) {
            return R.error(400, HtmlUtils.htmlEscape("实付金额必须大于0"));
        }
        if (orders.getStatus() == null) {
            return R.error(400, HtmlUtils.htmlEscape("订单状态不能为空"));
        }
        try {
            // 调用服务层方法，更新订单的实际支付金额
            int i = ordersService.updateRealpayInt(orders);
            return R.success(i);
        } catch (DataAccessException e) { // 假设这是数据库操作相关的异常
            return R.error(500, HtmlUtils.htmlEscape("更新失败: " + e.getMessage()));
        } catch (IllegalArgumentException e) { // 捕获非法参数异常
            return R.error(400, HtmlUtils.htmlEscape("非法参数: " + e.getMessage()));
        } catch (Exception e) {
            return R.error(500, HtmlUtils.htmlEscape("未知异常: " + e.getMessage()));
        }
    }

    /**
     * 上传订单图片
     *
     * @param id   订单ID
     * @param file 图片文件
     * @return 返回一个表示操作结果的响应对象
     */
    @PostMapping("/uploadImage/{id}")
    public R uploadImage(@PathVariable String id, @RequestParam("file") MultipartFile file) {
        // 检查上传的文件是否为空
        if (file.isEmpty()) {
            return R.error(400, "上传的文件不能为空");
        }
        try {
            Orders orders = new Orders();
            orders.setId(id);
            orders.setDelivery(file.getBytes());
            // 调用服务层方法上传图片
            int i = ordersService.uploadOrderImage(orders);
            // 根据上传结果返回相应的响应
            if (i > 0) {
                return R.success("图片上传成功");
            } else {
                return R.error(500, "图片上传失败");
            }
        } catch (IOException e) {
            // 处理文件读取异常
            return R.error(500, "文件读取失败");
        }
    }

    /**
     * 根据ID选择订单
     * <p>
     * 该方法通过接收一个ID参数来查询相关的订单信息如果ID无效或不存在于数据库中，
     * 则返回错误响应如果查询成功，则返回包含订单信息的成功响应
     *
     * @param id 要查询的订单ID，必须是正整数
     * @return 返回一个R对象，包含查询结果或错误信息
     */
    @PostMapping("/selectbyid/{id}")
    public R selectid(@PathVariable Integer id) {
        // 检查提供的ID是否有效
        if (id == null || id <= 0) {
            return R.error(400, "无效的 ID");
        }
        try {
            // 尝试根据ID获取订单列表
            List<Orders> orders = getOrdersById(id);
            // 检查返回的订单列表是否为空
            if (orders.isEmpty()) {
                return R.error(400, "未找到相关订单");
            }
            // 返回包含订单信息的成功响应
            return R.success(orders);
        } catch (Exception e) {
            // 记录异常日志
            return R.error(400, "查询订单时发生错误");
        }
    }

    @GetMapping("selectorder1/{oid}")
    public R caid1(@PathVariable String oid) {
        Map maps = ordersService.selectOrderDetail2(oid);

        return R.success(maps);
    }

    @PostMapping("selectorder2")
    public R caid2(@RequestBody Map map) {
        List<Map> maps = ordersService.selectOrderDetail1(map);
        return R.success(maps);
    }

    /**
     * 根据订单ID获取订单信息
     * <p>
     * 此方法通过调用OrdersService中的selectid方法来查询特定ID的订单信息
     * 选择使用私有访问权限是因为此方法仅在本类内部使用，不对外部开放
     *
     * @param id 订单ID，用于查询特定订单的信息
     * @return List<Orders> 返回一个Orders对象的列表，包含所有与指定ID匹配的订单
     * 如果没有找到匹配的订单，返回的列表将为空
     */
    private List<Orders> getOrdersById(Integer id) {
        return ordersService.selectid(id);
    }




}

